<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/4/23
 * Time: 17:55
 */
namespace app\api\controller;

use app\api\model\verticalDb;
use think\Controller;
use think\Request;
use think\Db;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;


/**
 * 文件上传
 */
class Upload extends Common{

    /**
     * 文件上传到七牛云
     * file
     */
    public function uploadFile(Request $request){

        if(Request::instance()->isPost()){
            //$data = input('post.');
            //上传操作
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/qnyFile');
                //获取后缀名
                $file = $info->getInfo('name');
                $arr = explode('.', $file);
                $type = end($arr);
                $filepath = $info->getPathname();
                if($info){
                    //上传七牛云
                    $res = $this->uploadQny($filepath,$info->getFilename());
                    if(isset($res['path'])){
                        $insertData = [
                            'path' =>$res['path'],
                            'full_path' =>$res['full_path'].'/'.$res['path'],
                            'type' =>$type,
                            'duration' =>0,
                        ];
                        $id = DB::table('file_upload')->insertGetId($insertData);
                        $insertData['id'] = $id;
                        unset($info);
                        @unlink($filepath);
                        self::$result_data['data'] = $insertData;
                    }else{
                        self::$result_data['msg'] = $res['msg'];
                    }

                }else{
                    // 上传失败获取错误信息
                    self::$result_data['msg'] = $file->getError();
                    $this->returnJson(self::$result_data);
                }
            }else{
                self::$result_data['msg'] = 'file error';
                $this->returnJson(self::$result_data);
            }


            $this->returnJson(self::$result_data);
        }

    }


    /**
     * 根据ID获取上传详情
     */
    public function getUploadInfo(Request $request){
        if(Request::instance()->isPost()){
            $id = input('post.id');
            if(!$id){
                self::$result_data['msg'] = 'id不能为空';
                $this->returnJson(self::$result_data);
            }
            $res = DB::table('file_upload')->where('id',$id)->find();
            //删除七牛云上的记录

            DB::table('file_upload')->where('id',$id)->delete();
            self::$result_data['code'] = 1;
            self::$result_data['data'] = $res;
            $this->returnJson(self::$result_data);
        }
    }

    /**
     * 根据ID删除数据库记录和七牛云文件
     */
    public function delUpload(Request $request){
        if(Request::instance()->isPost()){
            $id = input('post.id');
            if(!$id){
                self::$result_data['msg'] = 'id不能为空';
                $this->returnJson(self::$result_data);
            }
            $res = DB::table('file_upload')->where('id',$id)->find();
            $this->delQny($res['path']);
            DB::table('file_upload')->where('id',$id)->delete();
            self::$result_data['code'] = 1;
            $this->returnJson(self::$result_data);
        }
    }

    /**
     * 上传七牛云操作
     */
    public function uploadQny($filePath,$key){
        require_once APP_PATH . '/../vendor/qiniu-php-sdk-7.2.2/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config('BUCKET');
        $domain = config('DOMAIN');
        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return ["err"=>1,"msg"=>$err,"data"=>""];
        } else {
            //返回图片的完整URL
            return [
                'path'=>$ret['key'],
                'full_path'=>$domain,
            ];
        }
    }

    /**
     * 删除七牛云操作
     */
    public function delQny($fileName){
        require_once APP_PATH . '/../vendor/qiniu-php-sdk-7.2.2/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config('BUCKET');
        $token = $auth->uploadToken($bucket);
        $bucketMgr = new BucketManager($auth);
        $bucketMgr->delete($bucket,$fileName);
    }

}